# coding=utf-8
import datetime
import traceback

import xlwt
# pip install pyqt5 -i https://pypi.tuna.tsinghua.edu.cn/simple
# pip install pyqt5-tools -i https://pypi.tuna.tsinghua.edu.cn/simple
# pip install PyQtWebEngine -i https://pypi.tuna.tsinghua.edu.cn/simple
# pip install pynput -i https://pypi.tuna.tsinghua.edu.cn/simple
# pip install pyautogui -i https://pypi.tuna.tsinghua.edu.cn/simple
# pip install time -i https://pypi.tuna.tsinghua.edu.cn/simple
# pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple
# pip install yaml -i https://pypi.tuna.tsinghua.edu.cn/simple
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QHBoxLayout, QMessageBox, \
    QDialog, QLabel, QFileDialog

from logs.log import get_log
from ui.BaseWin import BaseWin

log = get_log("TableUi")


class Label(QLabel):
    clicked = pyqtSignal()

    def __init__(self, text):
        super().__init__(text)

    def mousePressEvent(self, event):
        self.clicked.emit()


class ResultUi(QDialog):

    def __init__(self, app, result):
        super(ResultUi, self).__init__()
        self.app = app
        self.result = result
        self.init_ui()
        # self.setWindowFlag(QtCore.Qt.WindowType.WindowStaysOnTopHint, True)

    def init_ui(self):
        self.resize(350, 150)
        self.setWindowTitle("执行结果(点击数字下载)")
        layout = QHBoxLayout()
        total = len(self.result)
        layout.addWidget(QLabel("总执行："))

        total_label = Label(str(total))
        total_label.clicked.connect(self.total_click)

        layout.addWidget(total_label)
        layout.addWidget(QLabel("，成功："))
        success_list = list(filter(lambda x: x['success'] == True, self.result))
        success_count = len(success_list)

        success_label = Label(str(success_count))
        success_label.clicked.connect(self.success_click)

        layout.addWidget(success_label)
        layout.addWidget(QLabel("，失败："))

        fail_label = Label(str(total - success_count))
        fail_label.clicked.connect(self.fail_click)

        layout.addWidget(fail_label)
        # 将网格布局应用到当前窗口
        self.setLayout(layout)
        self.setWindowIcon(QIcon('./configuration/favicon.ico'))
        self.set_center()

    def set_center(self):
        desktop = self.app.desktop()
        # 需要int类型的数据，float可能在后续版本会删除
        self.move(int((desktop.width() / 2 - self.width() / 2)), int((desktop.height() - self.height()) / 2))

    def closeEvent(self, event):
        pass

    def total_click(self):
        if not self.result or len(self.result) == 0:
            return
        self.write_excel_single(self.result)

    def success_click(self):
        if not self.result or len(self.result) == 0:
            return
        success_list = list(filter(lambda x: x['success'] == True, self.result))
        if not success_list or len(success_list) == 0:
            return
        self.write_excel_single(success_list)

    def fail_click(self):
        if not self.result or len(self.result) == 0:
            return
        fail_list = list(filter(lambda x: x['success'] == False, self.result))
        if not fail_list or len(fail_list) == 0:
            return
        self.write_excel_single(fail_list)

    def write_excel_single(self, data):
        directory = QFileDialog.getSaveFileName(self, "设置路径", "./", "excel(*.xls)")
        if not directory or len(directory) == 0 or not directory[0]:
            return
        print(directory[0])
        try:
            item = data[0]
            heads = []
            for key in item:
                heads.append(key)
            self.write_excel(heads, data, directory[0])
        except BaseException as e:
            log.error(traceback.format_exc())
            print(e)

    def write_excel(self, heads, data, path):
        workbook = xlwt.Workbook(encoding='utf-8', style_compression=0)
        sheet = workbook.add_sheet('执行结果', cell_overwrite_ok=False)
        # style = xlwt.XFStyle()
        index = 0
        for head in heads:
            sheet.write(0, index, head)
            sheet.col(index).width = 256 * 25
            index = index + 1
        line = 1
        for item in data:
            idx = 0
            for head in heads:
                sheet.write(line, idx, str(item[head]))
                idx = idx + 1
            line = line + 1
        # time_str = datetime.datetime.now().strftime("%Y年%m月%d日-%H点%M分%S秒")
        # workbook.save(f'./{time_str}.xls')
        workbook.save(path)
        # QMessageBox.information(self, "提示", "文件存储成功(在文件安装目录)")
